<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>填写投保信息 - 液化气用户家财险</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .modal {
            display: none;
            position: fixed;
            bottom: -100%;
            left: 0;
            right: 0;
            background: white;
            transform: translateY(100%);
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            max-height: 90vh;
            z-index: 1100;
        }
        .modal.show {
            transform: translateY(0);
            bottom: 0;
        }
        .modal-backdrop {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            opacity: 0;
            transition: opacity 0.3s ease;
            z-index: 1050;
        }
        .modal-backdrop.show {
            display: block;
            opacity: 1;
        }
        .user-type-button {
            position: relative;
            transition: all 0.3s ease;
        }
        .user-type-button:not(.active):hover {
            @apply border-blue-600 text-blue-600;
        }
        .user-type-button.active {
            @apply bg-blue-600 text-white font-medium border-blue-600;
        }
        /* 表单样式 */
        .form-label {
            @apply text-[15px] text-gray-600 font-medium;
        }
        .form-input {
            @apply w-full h-[40px] px-3 border-0 border-b-2 border-gray-300 text-[15px] focus:border-blue-600 focus:ring-0 transition-colors bg-white hover:border-gray-400;
        }
        .form-select {
            @apply w-full h-[40px] px-3 pr-8 border-0 border-b-2 border-gray-300 text-[15px] focus:border-blue-600 focus:ring-0 transition-colors appearance-none bg-white hover:border-gray-400 bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20fill%3D%22none%22%20viewBox%3D%220%200%2020%2020%22%3E%3Cpath%20stroke%3D%22%236b7280%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%221.5%22%20d%3D%22M6%208l4%204%204-4%22%2F%3E%3C%2Fsvg%3E')] bg-[length:1.5em_1.5em] bg-[right_0.5rem_center] bg-no-repeat;
        }
        .form-radio {
            @apply w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-600;
        }
        /* 操作按钮样式 */
        .action-button {
            @apply h-[40px] px-6 rounded-lg text-[15px] transition-colors flex items-center justify-center gap-2;
        }
        .action-button-primary {
            @apply bg-blue-600 text-white hover:bg-blue-700;
        }
        .action-button-secondary {
            @apply border border-gray-300 text-gray-600 hover:border-blue-600 hover:text-blue-600 hover:bg-blue-50;
        }
        .action-button-success {
            @apply bg-green-50 text-green-600 border border-green-100;
        }
        .action-button i {
            @apply text-[18px];
        }
        /* 自定义上传按钮样式 */
        .upload-button {
            @apply relative inline-flex items-center justify-center h-[40px] px-4 border border-gray-300 rounded-lg text-[15px] text-gray-600 bg-white hover:border-blue-600 hover:text-blue-600 transition-colors cursor-pointer;
        }
        .upload-button input[type="file"] {
            @apply absolute inset-0 w-full h-full opacity-0 cursor-pointer;
        }
        /* 表格样式 */
        .table-container {
            @apply overflow-x-auto;
        }
        .data-table {
            @apply min-w-full divide-y divide-gray-200;
        }
        .data-table th {
            @apply px-4 py-3 text-left text-[13px] font-medium text-gray-500 uppercase tracking-wider bg-gray-50;
        }
        .data-table td {
            @apply px-4 py-3 text-[15px] text-gray-900 border-b;
        }
        /* 分页样式 */
        .pagination {
            @apply flex items-center justify-center space-x-2 mt-4;
        }
        .pagination-button {
            @apply w-8 h-8 flex items-center justify-center border rounded-lg text-[15px] transition-colors;
        }
        .pagination-button.active {
            @apply bg-blue-600 text-white border-blue-600;
        }
        .pagination-button:not(.active) {
            @apply text-gray-600 border-gray-300 hover:border-blue-600 hover:text-blue-600;
        }
        /* 操作按钮样式 */
        .action-button {
            @apply h-[40px] px-6 rounded-lg text-[15px] transition-colors;
        }
        .action-button-primary {
            @apply bg-blue-600 text-white hover:bg-blue-700;
        }
        .action-button-secondary {
            @apply border border-gray-300 text-gray-600 hover:border-blue-600 hover:text-blue-600;
        }
        .action-button-success {
            @apply bg-green-50 text-green-600 border border-green-100;
        }
        
        /* 进入投保流程提示弹窗样式 */
        .entrance-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .entrance-modal.show {
            display: flex;
            opacity: 1;
        }
        .entrance-modal-content {
            position: fixed;
            bottom: -100%;
            left: 0;
            right: 0;
            background: white;
            border-radius: 16px 16px 0 0;
            padding: 24px;
            margin: 0 16px 16px 16px;
            max-height: 70vh;
            overflow-y: auto;
            transition: bottom 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .entrance-modal.show .entrance-modal-content {
            bottom: 0;
        }
        
        /* 保障方案样式 */
        .plan-selector {
            display: flex;
            gap: 8px;
            margin-bottom: 16px;
        }
        .plan-button {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            background: white;
            color: #6b7280;
            font-size: 14px;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .plan-button.active {
            background: #2563eb;
            color: white;
            border-color: #2563eb;
        }
        
        /* 数量选择器样式 */
        .quantity-selector {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .quantity-button {
            width: 32px;
            height: 32px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .quantity-button:hover {
            border-color: #2563eb;
            color: #2563eb;
        }
        .quantity-input {
            width: 60px;
            height: 32px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            text-align: center;
            font-size: 14px;
        }
        
        /* PDF容器样式 */
        .pdf-container {
            background: #f9fafb;
            border-radius: 8px;
            padding: 16px;
        }
        
        .pdf-page {
            margin-bottom: 16px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border-radius: 4px;
            overflow: hidden;
        }
        
        .loading-indicator {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 200px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-100">
    <!-- 进入投保流程提示弹窗 -->
    <div class="entrance-modal" id="entranceModal">
        <div class="entrance-modal-content">
            <h3 class="text-xl font-bold mb-4 text-center">进入投保流程提示</h3>
            <div class="space-y-4 text-sm text-gray-600 leading-relaxed">
                <p>您已进入投保流程，本产品由XX财产保险股份有限公司承保，由世纪保险经纪有限责任公司代理销售。</p>
                <p>请在完成投保之前仔细阅读保险条款、投保须知、<a href="#" onclick="showAuthModal()" class="text-blue-600 underline">授权委托书</a>、<a href="#" onclick="showNoticeModal()" class="text-blue-600 underline">客户告知书</a>等内容并关注承保保险公司信息。</p>
                <p>为保障您的权益，我们将会安全记录您的操作。</p>
            </div>
            <button onclick="confirmStartInsurance()" class="w-full mt-6 bg-blue-600 text-white py-3 rounded-lg font-medium">
                确认开始投保
            </button>
        </div>
    </div>

    <!-- 授权委托书弹窗 -->
    <div class="modal rounded-t-2xl" id="authModal">
        <div class="p-4 h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold">授权委托书</h3>
                <button onclick="hideModal('authModal')" class="text-gray-500 p-2">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="flex-1 overflow-y-auto">
                <div id="authPdfContainer" class="w-full h-full min-h-[70vh] bg-gray-50 flex flex-col items-center justify-center">
                    <div class="loading-indicator">
                        <i class="fas fa-spinner fa-spin text-2xl text-gray-400 mb-2"></i>
                        <p class="text-gray-500">正在加载文档...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 客户告知书弹窗 -->
    <div class="modal rounded-t-2xl" id="noticeModal">
        <div class="p-4 h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold">客户告知书</h3>
                <button onclick="hideModal('noticeModal')" class="text-gray-500 p-2">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="flex-1 overflow-y-auto">
                <div id="noticePdfContainer" class="w-full h-full min-h-[70vh] bg-gray-50 flex flex-col items-center justify-center">
                    <div class="loading-indicator">
                        <i class="fas fa-spinner fa-spin text-2xl text-gray-400 mb-2"></i>
                        <p class="text-gray-500">正在加载文档...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 固定的产品标题区域 -->
    <div class="fixed top-0 left-0 right-0 bg-white p-4 border-b shadow-sm z-[999]">
        <h1 class="text-xl font-bold text-gray-900">液化气用户家财险</h1>
        <p class="text-sm text-gray-500">保险公司：人保财险</p>
    </div>

    <!-- 页面主体 -->
    <div class="pb-[72px] pt-[76px]">

        <!-- 保障方案选择 -->
        <div class="bg-white mt-2 p-4">
            <h2 class="text-[17px] font-bold mb-4">选择保障方案</h2>
            <div class="plan-selector mb-4">
                <button class="plan-button active" data-plan="basic" onclick="selectPlan('basic')">基础款</button>
                <button class="plan-button" data-plan="upgrade" onclick="selectPlan('upgrade')">升级款</button>
                <button class="plan-button" data-plan="premium" onclick="selectPlan('premium')">尊享款</button>
            </div>
            
            <!-- 保障内容详情 -->
            <div class="space-y-3 text-sm" id="planDetails">
                <!-- 动态内容 -->
            </div>
            
            <!-- 投保份数 -->
            <div class="mt-6">
                <h3 class="text-[16px] font-medium mb-3">投保份数</h3>
                <div class="quantity-selector">
                    <button class="quantity-button" onclick="changeQuantity(-1)">
                        <i class="fas fa-minus"></i>
                    </button>
                    <input type="number" class="quantity-input" id="insuranceQuantity" value="1" min="1" onchange="updatePremium()">
                    <button class="quantity-button" onclick="changeQuantity(1)">
                        <i class="fas fa-plus"></i>
                    </button>
                    <span class="text-sm text-gray-600">份</span>
                </div>
            </div>
        </div>

        <!-- 保险期间 -->
        <div class="bg-white mt-2 p-4">
            <h2 class="text-[17px] font-bold mb-4">保险期间</h2>
            <div class="space-y-4">
                <div class="flex items-center">
                    <label class="form-label w-24">保险起期</label>
                    <div class="flex-1 relative group cursor-text" onclick="focusInput(this)">
                        <input type="datetime-local" id="startDate" class="form-input pr-10" onchange="updateEndDate()">
                        <i class="fas fa-calendar-alt absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 group-hover:text-blue-600 pointer-events-none"></i>
                    </div>
                </div>
                <div class="flex items-center">
                    <label class="form-label w-24">保险止期</label>
                    <div class="flex-1 relative group">
                        <input type="datetime-local" id="endDate" class="form-input pr-10 bg-gray-50" readonly>
                        <i class="fas fa-calendar-alt absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                    </div>
                </div>
                <p class="text-xs text-gray-500">保险期间为1年，保险止期将自动计算</p>
            </div>
        </div>

        <!-- 填写投保客户资料 -->
        <div id="personalInfo" class="bg-white mt-2 p-4 space-y-6">
            <h2 class="text-[17px] font-bold">填写投保客户资料</h2>
            <!-- 身份证OCR上传占位（个人） -->
            <div class="space-y-2">
                <label class="form-label block">身份证识别</label>
                <div id="personalIdUploadArea" class="relative group cursor-pointer hover:opacity-90 transition-opacity">
                    <input type="file" accept="image/*" capture="environment" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" onchange="handlePersonalIdUpload(this)">
                    <div class="w-full h-[140px] border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center bg-gray-50 group-hover:border-blue-600 group-hover:bg-blue-50">
                        <i class="fas fa-id-card text-[40px] mb-3 text-gray-400 group-hover:text-blue-600"></i>
                        <p class="text-[15px] text-gray-600 group-hover:text-blue-600">上传或拍照识别身份证</p>
                        <p class="text-[13px] text-gray-400 mt-1">支持 PNG、JPG 等图片格式</p>
                    </div>
                </div>
                <div class="hidden" id="personalIdPreview">
                    <div class="relative">
                        <img src="" alt="身份证预览" class="w-full h-[140px] object-cover bg-gray-50 rounded-lg border border-gray-200">
                        <div class="absolute top-2 right-2 flex gap-2">
                            <button onclick="removePersonalId()" class="bg-gray-800/70 hover:bg-red-600 text-white rounded-full w-8 h-8 flex items-center justify-center backdrop-blur-sm transition-colors">
                                <i class="fas fa-times text-sm"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 投保人姓名 -->
            <div class="flex items-center">
                <label class="form-label w-32">投保人姓名</label>
                <div class="flex-1 relative group cursor-text" onclick="focusInput(this)">
                    <input type="text" class="form-input pr-10" placeholder="请输入投保人姓名">
                    <i class="fas fa-edit absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 group-hover:text-blue-600 pointer-events-none"></i>
                </div>
            </div>

            <!-- 证件类型 -->
            <div class="flex items-center">
                <label class="form-label w-32">证件类型</label>
                <div class="flex-1">
                    <select class="form-select" onchange="handleIdTypeChange(this.value)">
                        <option value="idcard">身份证号码</option>
                        <option value="passport">护照</option>
                        <option value="residence">居住证</option>
                    </select>
                </div>
            </div>

            <!-- 证件号码 -->
            <div class="flex items-center">
                <label class="form-label w-32">证件号码</label>
                <div class="flex-1 relative group cursor-text" onclick="focusInput(this)">
                    <input type="text" class="form-input pr-10" placeholder="请输入投保人证件号码" onchange="handleIdNumberChange(this.value)">
                    <i class="fas fa-edit absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 group-hover:text-blue-600 pointer-events-none"></i>
                </div>
            </div>

            <!-- 投保人性别 -->
            <div class="flex items-center">
                <label class="form-label w-32">投保人性别</label>
                <div class="flex gap-2">
                    <button type="button" class="personal-gender-button w-16 h-8 rounded-lg border border-gray-300 text-gray-600 text-[14px] transition-colors" data-value="male">男</button>
                    <button type="button" class="personal-gender-button w-16 h-8 rounded-lg border border-gray-300 text-gray-600 text-[14px] transition-colors" data-value="female">女</button>
                    <input type="hidden" id="personalGenderValue" value="">
                </div>
            </div>

            <!-- 投保人出生日期 -->
            <div class="flex items-center">
                <label class="form-label w-32">出生日期</label>
                <div class="flex-1 relative group cursor-text" onclick="focusInput(this)">
                    <input type="date" class="form-input pr-10">
                    <i class="fas fa-calendar-alt absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 group-hover:text-blue-600 pointer-events-none"></i>
                </div>
            </div>

                <!-- 手机号（个人） -->
                <div class="flex items-center">
                    <label class="form-label w-32">手机号</label>
                    <div class="flex-1 relative group cursor-text" onclick="focusInput(this)">
                        <input type="tel" id="personalPhone" class="form-input pr-10" placeholder="请输入投保人手机号">
                        <i class="fas fa-mobile-alt absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 group-hover:text-blue-600 pointer-events-none"></i>
                    </div>
                </div>
                
                <!-- 获取验证码按钮 -->
                <div class="flex items-center">
                    <div class="w-32"></div>
                    <div class="flex-1">
                        <button type="button" id="getCodeBtn" onclick="sendPersonalCode()" class="w-24 h-[36px] px-3 text-[13px] rounded border border-blue-600 text-blue-600 hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed">获取验证码</button>
                    </div>
                </div>

                <!-- 验证码（个人） -->
                <div class="flex items-center">
                    <label class="form-label w-32">验证码</label>
                    <div class="flex-1 relative group cursor-text" onclick="focusInput(this)">
                        <input type="text" id="personalCode" class="form-input pr-10" placeholder="请输入验证码">
                        <i class="fas fa-lock absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 group-hover:text-blue-600 pointer-events-none"></i>
                    </div>
                </div>

                <!-- 电子邮箱（个人） -->
                <div class="flex items-center">
                    <label class="form-label w-32">电子邮箱</label>
                    <div class="flex-1 relative group cursor-text" onclick="focusInput(this)">
                        <input type="email" id="personalEmail" class="form-input pr-10" placeholder="用于接收电子保单">
                        <i class="fas fa-envelope absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 group-hover:text-blue-600 pointer-events-none"></i>
                    </div>
                </div>

                <!-- 燃气用户（卡）号 -->
                <div class="flex items-center">
                    <label class="form-label w-32">液化气用户（卡）号</label>
                    <div class="flex-1 relative group cursor-text" onclick="focusInput(this)">
                        <input type="text" id="gasUserNumber" class="form-input pr-10" placeholder="请输入液化气用户号或卡号">
                        <i class="fas fa-credit-card absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 group-hover:text-blue-600 pointer-events-none"></i>
                    </div>
                </div>

                <!-- 被保险家庭地址 -->
                <div class="space-y-3">
                    <label class="form-label block">被保险家庭地址</label>
                    <!-- 省市区选择 -->
                    <div class="grid grid-cols-3 gap-3">
                        <select id="province" class="form-select" onchange="loadCities()">
                            <option value="">选择省份</option>
                            <option value="beijing">北京市</option>
                            <option value="shanghai">上海市</option>
                            <option value="guangdong">广东省</option>
                            <option value="zhejiang">浙江省</option>
                            <option value="jiangsu">江苏省</option>
                        </select>
                        <select id="city" class="form-select" onchange="loadDistricts()">
                            <option value="">选择地市</option>
                        </select>
                        <select id="district" class="form-select">
                            <option value="">选择县区</option>
                        </select>
                    </div>
                    <!-- 详细地址 -->
                    <div class="relative group cursor-text" onclick="focusInput(this)">
                        <input type="text" id="detailedAddress" class="form-input pr-10 w-full min-w-[300px]" placeholder="请输入被保险地址，精确到门牌号">
                        <i class="fas fa-map-marker-alt absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 group-hover:text-blue-600 pointer-events-none"></i>
                    </div>
                </div>
        </div>

        <!-- 必须阅读文件 -->
        <div class="bg-white mt-2 p-4">
            <h2 class="text-[17px] font-bold mb-4">必须阅读文件</h2>
            <div class="space-y-3">
                <!-- 复选框和标题区域 -->
                <div class="flex items-start gap-3 cursor-pointer" onclick="event.preventDefault(); event.stopPropagation(); showToast('请先阅读必须阅读文件区域所有告知文件和条款', 'error'); return false;">
                    <input type="checkbox" id="readAllDocuments" class="form-checkbox mt-1" disabled onclick="event.preventDefault(); event.stopPropagation(); showToast('请先阅读必须阅读文件区域所有告知文件和条款', 'error'); return false;">
                    <p class="text-sm text-gray-900">我已阅读并同意以下全部文件：</p>
                </div>
                
                <!-- 文件列表区域 -->
                <div class="ml-7 space-y-2 text-sm">
                    <div class="flex items-center justify-between">
                        <span class="text-blue-600 cursor-pointer" onclick="openDocument('客户告知书')">《客户告知书》</span>
                        <span class="text-xs text-gray-400" id="status-客户告知书">未阅读</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-blue-600 cursor-pointer" onclick="openDocument('授权委托书')">《授权委托书》</span>
                        <span class="text-xs text-gray-400" id="status-授权委托书">未阅读</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-blue-600 cursor-pointer" onclick="openDocument('用户须知')">《用户须知》</span>
                        <span class="text-xs text-gray-400" id="status-用户须知">未阅读</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-blue-600 cursor-pointer" onclick="openDocument('免责条款')">《免责条款》</span>
                        <span class="text-xs text-gray-400" id="status-免责条款">未阅读</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-blue-600 cursor-pointer" onclick="openDocument('液化气用户家财险条款')">《液化气用户家财险条款》</span>
                        <span class="text-xs text-gray-400" id="status-液化气用户家财险条款">未阅读</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部固定栏 -->
    <div class="fixed bottom-0 left-0 right-0 bg-white border-t p-4 flex items-center justify-between">
        <div class="text-sm">
            总保费 <span class="text-red-600 font-bold text-lg" id="totalPremium">10</span> 元
        </div>
        <button class="bg-blue-600 text-white px-8 py-2 rounded-full" onclick="validateAndSubmit()">
            下一步
        </button>
    </div>

    <!-- 文档阅读弹窗 -->
    <div class="modal rounded-t-2xl" id="documentModal">
        <div class="p-4 h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold" id="documentTitle">文档标题</h3>
                <button onclick="hideModal('documentModal')" class="text-gray-500 p-2">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="flex-1 overflow-y-auto mb-4">
                <div id="documentContent" class="w-full h-full min-h-[70vh] bg-gray-50 flex flex-col items-center justify-center">
                    <div class="loading-indicator">
                        <i class="fas fa-spinner fa-spin text-2xl text-gray-400 mb-2"></i>
                        <p class="text-gray-500">正在加载文档...</p>
                    </div>
                </div>
            </div>
            <button id="nextDocumentBtn" onclick="nextDocument()" class="w-full bg-blue-600 text-white py-3 rounded-lg font-medium">
                阅读下一个
            </button>
        </div>
    </div>



    <!-- 遮罩层 -->
    <div class="modal-backdrop" id="modalBackdrop"></div>

    <script>
        // 保障方案数据
        const plans = {
            basic: {
                name: '基础款',
                premium: 10,
                details: [
                    { label: '保障期间', value: '1年' },
                    { label: '投保年龄', value: '18周岁(含)-90周岁(含)' },
                    { label: '室内财产损失', value: '5万/户' },
                    { label: '人身意外身故残疾及意外医疗（三者）', value: '2万/人' },
                    { label: '人身意外身故/残疾', value: '2万/人' },
                    { label: '意外医疗', value: '5000元/人' }
                ]
            },
            upgrade: {
                name: '升级款',
                premium: 20,
                details: [
                    { label: '保障期间', value: '1年' },
                    { label: '投保年龄', value: '18周岁(含)-90周岁(含)' },
                    { label: '室内财产损失', value: '10万/户' },
                    { label: '人身意外身故残疾及意外医疗（三者）', value: '5万/人' },
                    { label: '人身意外身故/残疾', value: '5万/人' },
                    { label: '意外医疗', value: '1万/人' }
                ]
            },
            premium: {
                name: '尊享款',
                premium: 25,
                details: [
                    { label: '保障期间', value: '1年' },
                    { label: '投保年龄', value: '18周岁(含)-90周岁(含)' },
                    { label: '室内财产损失', value: '20万/户' },
                    { label: '人身意外身故残疾及意外医疗（三者）', value: '10万/人' },
                    { label: '人身意外身故/残疾', value: '10万/人' },
                    { label: '意外医疗', value: '2万/人' }
                ]
            }
        };

        // 当前选中的方案和数量
        let currentPlan = 'basic';
        let currentQuantity = 1;

        // 文档阅读状态
        const documents = ['客户告知书', '授权委托书', '用户须知', '免责条款', '液化气用户家财险条款'];
        let readDocuments = [];
        let currentDocumentIndex = 0;

        // 弹窗控制
        function showModal(modalId) {
            const modal = document.getElementById(modalId);
            const backdrop = document.getElementById('modalBackdrop');
            
            modal.style.display = 'block';
            backdrop.classList.add('show');
            setTimeout(() => {
                modal.classList.add('show');
            }, 10);
        }

        function hideModal(modalId) {
            const modal = document.getElementById(modalId);
            const backdrop = document.getElementById('modalBackdrop');
            
            modal.classList.remove('show');
            setTimeout(() => {
                modal.style.display = 'none';
                backdrop.classList.remove('show');
            }, 300);
        }

        // 文档图片加载相关函数
        function loadDocument(containerSelector, docName) {
            const container = document.querySelector(containerSelector);
            if (!container) return;

            // 清空容器
            container.innerHTML = '';
            container.classList.remove('flex', 'flex-col', 'items-center', 'justify-center');

            // 获取对应的图片路径
            const imagePath = getDocumentImagePath(docName);
            
            // 直接加载图片
            loadDocumentImage(container, imagePath, docName);
        }

        // 获取文档对应的图片路径
        function getDocumentImagePath(docName) {
            // 文件名映射
            const fileNameMap = {
                '客户告知书': '客户告知书.png',
                '授权委托书': '授权委托书（个人）.png',
                '用户须知': '投保须知.png',
                '免责条款': '免责条款.png',
                '液化气用户家财险条款': '液化气用户家财险条款.png'
            };
            
            const fileName = fileNameMap[docName];
            return fileName ? `../${fileName}` : null;
        }

        // 加载文档图片
        function loadDocumentImage(container, imagePath, docName) {
            if (!container || !imagePath) {
                container.innerHTML = `
                    <div class="flex flex-col items-center justify-center py-8">
                        <i class="fas fa-exclamation-triangle text-2xl text-yellow-500 mb-2"></i>
                        <p class="text-gray-600">暂无可显示的文档图片</p>
                        <p class="text-xs text-gray-500 mt-1">请联系管理员上传文档图片</p>
                    </div>
                `;
                return;
            }

            // 显示加载状态
            container.innerHTML = `
                <div class="flex flex-col items-center justify-center py-8">
                    <i class="fas fa-spinner fa-spin text-2xl text-gray-400 mb-2"></i>
                    <p class="text-gray-500">正在加载文档...</p>
                </div>
            `;

            const img = document.createElement('img');
            img.className = 'w-full max-w-full h-auto';
            img.alt = docName;
            img.style.objectFit = 'contain';
            
            // 图片加载成功
            img.onload = function() {
                container.innerHTML = '';
                container.appendChild(img);
            };
            
            // 图片加载失败
            img.onerror = function() {
                container.innerHTML = `
                    <div class="flex flex-col items-center justify-center py-8">
                        <i class="fas fa-image text-2xl text-gray-400 mb-2"></i>
                        <p class="text-gray-600">文档图片加载失败</p>
                        <p class="text-xs text-gray-500 mt-1">图片路径: ${imagePath}</p>
                    </div>
                `;
            };
            
            img.src = imagePath;
        }

        // 进入投保流程提示相关函数
        function showAuthModal() {
            showModal('authModal');
            // 加载授权委托书文档
            setTimeout(() => {
                loadDocument('#authPdfContainer', '授权委托书');
            }, 300);
        }

        function showNoticeModal() {
            showModal('noticeModal');
            // 加载客户告知书文档
            setTimeout(() => {
                loadDocument('#noticePdfContainer', '客户告知书');
            }, 300);
        }

        function confirmStartInsurance() {
            hideEntranceModal();
        }

        function showEntranceModal() {
            const modal = document.getElementById('entranceModal');
            modal.classList.add('show');
        }

        function hideEntranceModal() {
            const modal = document.getElementById('entranceModal');
            modal.classList.remove('show');
        }

        // 保障方案选择
        function selectPlan(plan) {
            currentPlan = plan;
            
            // 更新按钮状态
            document.querySelectorAll('.plan-button').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelector(`[data-plan="${plan}"]`).classList.add('active');
            
            // 更新保障内容
            updatePlanDetails();
            updatePremium();
        }

        // 更新保障内容详情
        function updatePlanDetails() {
            const planData = plans[currentPlan];
            const detailsContainer = document.getElementById('planDetails');
            
            let html = '';
            planData.details.forEach(detail => {
                html += `
                    <div class="flex justify-between items-center py-2 border-b border-gray-100">
                        <span class="text-gray-600">${detail.label}</span>
                        <span class="font-medium ${detail.label.includes('损失') || detail.label.includes('身故') || detail.label.includes('伤残') ? 'text-red-600' : ''}">${detail.value}</span>
                    </div>
                `;
            });
            detailsContainer.innerHTML = html;
        }
        // 数量选择
        function changeQuantity(delta) {
            const input = document.getElementById('insuranceQuantity');
            let newValue = parseInt(input.value) + delta;
            if (newValue < 1) newValue = 1;
            
            input.value = newValue;
            currentQuantity = newValue;
            updatePremium();
        }

        // 更新总保费
        function updatePremium() {
            const planData = plans[currentPlan];
            const total = planData.premium * currentQuantity;
            document.getElementById('totalPremium').textContent = total;
        }

        // 保险起期变化时更新止期
        function updateEndDate() {
            const startDate = document.getElementById('startDate').value;
            if (startDate) {
                const start = new Date(startDate);
                const end = new Date(start.getTime() + 365 * 24 * 60 * 60 * 1000); // 加一年
                document.getElementById('endDate').value = end.toISOString().slice(0, 16);
            }
        }

        // 地区选择相关函数
        function loadCities() {
            const province = document.getElementById('province').value;
            const citySelect = document.getElementById('city');
            const districtSelect = document.getElementById('district');
            
            // 清空市和区
            citySelect.innerHTML = '<option value="">选择地市</option>';
            districtSelect.innerHTML = '<option value="">选择县区</option>';
            
            // 模拟城市数据
            if (province === 'beijing') {
                citySelect.innerHTML += '<option value="beijing">北京市</option>';
            } else if (province === 'guangdong') {
                citySelect.innerHTML += '<option value="guangzhou">广州市</option><option value="shenzhen">深圳市</option>';
            }
            // 其他省份的城市...
        }

        function loadDistricts() {
            const city = document.getElementById('city').value;
            const districtSelect = document.getElementById('district');
            
            // 清空区
            districtSelect.innerHTML = '<option value="">选择县区</option>';
            
            // 模拟区县数据
            if (city === 'beijing') {
                districtSelect.innerHTML += '<option value="chaoyang">朝阳区</option><option value="haidian">海淀区</option>';
            } else if (city === 'guangzhou') {
                districtSelect.innerHTML += '<option value="tianhe">天河区</option><option value="yuexiu">越秀区</option>';
            }
            // 其他城市的区县...
        }

        // 聚焦输入框
        function focusInput(container) {
            const input = container.querySelector('input');
            if (input) {
                input.focus();
                if (input.value) {
                    const len = input.value.length;
                    input.setSelectionRange(len, len);
                }
            }
        }

        // 文档阅读相关函数
        function openDocument(docName) {
            currentDocumentIndex = documents.indexOf(docName);
            document.getElementById('documentTitle').textContent = docName;
            
            // 更新按钮文本
            const btn = document.getElementById('nextDocumentBtn');
            if (currentDocumentIndex === documents.length - 1) {
                btn.textContent = '确定';
            } else {
                btn.textContent = '阅读下一个';
            }
            
            showModal('documentModal');
            
            // 加载文档图片
            setTimeout(() => {
                loadDocument('#documentContent', docName);
            }, 300);
        }

        function nextDocument() {
            // 标记当前文档为已读
            const currentDoc = documents[currentDocumentIndex];
            if (!readDocuments.includes(currentDoc)) {
                readDocuments.push(currentDoc);
                document.getElementById(`status-${currentDoc}`).textContent = '已阅读';
                document.getElementById(`status-${currentDoc}`).className = 'text-xs text-green-600';
            }

            if (currentDocumentIndex === documents.length - 1) {
                // 最后一个文档，关闭弹窗
                hideModal('documentModal');
                
                // 检查是否全部阅读完成
                if (readDocuments.length === documents.length) {
                    document.getElementById('readAllDocuments').disabled = false;
                    document.getElementById('readAllDocuments').checked = true;
                }
            } else {
                // 显示下一个文档
                currentDocumentIndex++;
                const nextDoc = documents[currentDocumentIndex];
                document.getElementById('documentTitle').textContent = nextDoc;
                
                // 加载下一个文档的图片
                loadDocument('#documentContent', nextDoc);
                
                // 更新按钮文本
                const btn = document.getElementById('nextDocumentBtn');
                if (currentDocumentIndex === documents.length - 1) {
                    btn.textContent = '确定';
                } else {
                    btn.textContent = '阅读下一个';
                }
            }
        }

        // 处理身份证OCR上传（个人）
        function handlePersonalIdUpload(input) {
            const file = input.files && input.files[0];
            if (!file) return;
            if (!file.type.startsWith('image/')) {
                showToast('请上传图片文件', 'error');
                input.value = '';
                return;
            }
            const reader = new FileReader();
            reader.onload = function(e) {
                const url = e.target.result;
                // 预览
                const preview = document.getElementById('personalIdPreview');
                preview.querySelector('img').src = url;
                preview.classList.remove('hidden');

                // 模拟OCR识别结果
                const mock = {
                    name: '张三',
                    idNumber: '110101199001012345'
                };
                // 回填姓名
                const nameInput = document.querySelector('#personalInfo input[placeholder="请输入投保人姓名"]');
                if (nameInput) nameInput.value = mock.name;
                // 回填证件号码
                const idNumberInput = document.querySelector('#personalInfo input[placeholder="请输入投保人证件号码"]');
                if (idNumberInput) {
                    idNumberInput.value = mock.idNumber;
                    // 触发解析性别和出生日期逻辑
                    handleIdNumberChange(mock.idNumber);
                }
            };
            reader.readAsDataURL(file);
        }

        function removePersonalId() {
            document.getElementById('personalIdPreview').classList.add('hidden');
            document.getElementById('personalIdPreview').querySelector('img').src = '';
            const input = document.querySelector('#personalIdUploadArea input[type="file"]');
            if (input) input.value = '';
        }

        // 处理身份证号码变化
        function handleIdNumberChange(idNumber) {
            if (idNumber.length === 18) {
                // 提取性别（倒数第二位，奇数为男，偶数为女）
                const gender = parseInt(idNumber.charAt(16)) % 2 === 1 ? 'male' : 'female';
                
                // 更新性别按钮状态
                document.querySelectorAll('.personal-gender-button').forEach(btn => {
                    const isSelected = btn.getAttribute('data-value') === gender;
                    btn.classList.toggle('bg-blue-600', isSelected);
                    btn.classList.toggle('text-white', isSelected);
                    btn.classList.toggle('border-blue-600', isSelected);
                    btn.classList.toggle('text-gray-600', !isSelected);
                    btn.classList.toggle('border-gray-300', !isSelected);
                });
                
                // 更新隐藏字段的值
                document.getElementById('personalGenderValue').value = gender;

                // 提取出生日期
                const birth = `${idNumber.substring(6, 10)}-${idNumber.substring(10, 12)}-${idNumber.substring(12, 14)}`;
                document.querySelector('#personalInfo input[type="date"]').value = birth;
            }
        }

        // 发送验证码
        function sendPersonalCode() {
            const btn = document.getElementById('getCodeBtn');
            if (!btn || btn.disabled) return;
            
            const phone = document.getElementById('personalPhone')?.value?.trim() || '';
            if (!/^1[3-9]\d{9}$/.test(phone)) {
                showToast('请先填写正确的手机号', 'error');
                return;
            }
            
            showToast('验证码已发送', 'success');
            let remaining = 60;
            btn.disabled = true;
            btn.textContent = `${remaining}s`;
            const timer = setInterval(() => {
                remaining--;
                if (remaining <= 0) {
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.textContent = '获取验证码';
                } else {
                    btn.textContent = `${remaining}s`;
                }
            }, 1000);
        }

        // 初始化个人性别按钮
        function initPersonalGenderButtons() {
            document.querySelectorAll('.personal-gender-button').forEach(button => {
                button.addEventListener('click', function() {
                    const value = this.getAttribute('data-value');
                    
                    // 更新按钮状态
                    document.querySelectorAll('.personal-gender-button').forEach(btn => {
                        const isSelected = btn.getAttribute('data-value') === value;
                        btn.classList.toggle('bg-blue-600', isSelected);
                        btn.classList.toggle('text-white', isSelected);
                        btn.classList.toggle('border-blue-600', isSelected);
                        btn.classList.toggle('text-gray-600', !isSelected);
                        btn.classList.toggle('border-gray-300', !isSelected);
                    });
                    
                    // 更新隐藏字段的值
                    document.getElementById('personalGenderValue').value = value;
                });
            });
        }

        // 处理必须阅读文件复选框点击
        function handleCheckboxClick(event) {
            const checkbox = document.getElementById('readAllDocuments');
            
            // 如果复选框被禁用，显示提示
            if (checkbox.disabled) {
                event.preventDefault();
                event.stopPropagation();
                showToast('请先阅读必须阅读文件区域所有告知文件和条款', 'error');
                return false;
            }
            
            // 如果复选框已启用但用户试图取消勾选，也显示提示
            if (checkbox.checked && !checkbox.disabled) {
                event.preventDefault();
                event.stopPropagation();
                showToast('请确保已完整阅读所有必须阅读的文件', 'error');
                return false;
            }
        }

        // 表单验证和提交
        function validateAndSubmit() {
            console.log('validateAndSubmit called');
            
            // 验证保障方案（必须有选择）
            if (!currentPlan) {
                console.log('Plan validation failed');
                showToast('请选择保障方案', 'error');
                return;
            }

            // 验证投保份数
            const quantityElement = document.getElementById('insuranceQuantity');
            if (!quantityElement) {
                console.log('Quantity element not found');
                showToast('页面元素错误，请刷新页面重试', 'error');
                return;
            }
            const quantity = parseInt(quantityElement.value);
            if (!quantity || quantity < 1) {
                console.log('Quantity validation failed:', quantity);
                showToast('投保份数不能少于1份', 'error');
                return;
            }

            // 验证保险起期和止期
            const startDateElement = document.getElementById('startDate');
            const endDateElement = document.getElementById('endDate');
            if (!startDateElement || !endDateElement) {
                console.log('Date elements not found');
                showToast('页面元素错误，请刷新页面重试', 'error');
                return;
            }
            const startDate = startDateElement.value;
            const endDate = endDateElement.value;
            if (!startDate) {
                console.log('Start date validation failed');
                showToast('请选择保险起期', 'error');
                return;
            }
            if (!endDate) {
                console.log('End date validation failed');
                showToast('保险止期异常，请重新选择起期', 'error');
                return;
            }

            // 验证投保人信息
            const nameElement = document.querySelector('#personalInfo input[placeholder="请输入投保人姓名"]');
            const idTypeSelect = document.querySelector('#personalInfo select');
            const idNumberElement = document.querySelector('#personalInfo input[placeholder="请输入投保人证件号码"]');
            const genderElement = document.getElementById('personalGenderValue');
            const birthDateElement = document.querySelector('#personalInfo input[type="date"]');
            const phoneElement = document.getElementById('personalPhone');
            const codeElement = document.getElementById('personalCode');
            const emailElement = document.getElementById('personalEmail');
            const gasUserNumberElement = document.getElementById('gasUserNumber');
            const provinceElement = document.getElementById('province');
            const cityElement = document.getElementById('city');
            const districtElement = document.getElementById('district');
            const detailedAddressElement = document.getElementById('detailedAddress');

            if (!nameElement || !idTypeSelect || !idNumberElement || !genderElement || 
                !birthDateElement || !phoneElement || !codeElement || !emailElement || 
                !gasUserNumberElement || !provinceElement || !cityElement || 
                !districtElement || !detailedAddressElement) {
                console.log('Some form elements not found');
                showToast('页面元素错误，请刷新页面重试', 'error');
                return;
            }

            const name = nameElement.value.trim();
            const idType = idTypeSelect.value;
            const idNumber = idNumberElement.value.trim();
            const gender = genderElement.value;
            const birthDate = birthDateElement.value;
            const phone = phoneElement.value.trim();
            const code = codeElement.value.trim();
            const email = emailElement.value.trim();
            const gasUserNumber = gasUserNumberElement.value.trim();
            const province = provinceElement.value;
            const city = cityElement.value;
            const district = districtElement.value;
            const detailedAddress = detailedAddressElement.value.trim();

            console.log('Form values:', { name, idType, idNumber, gender, birthDate, phone, code, email, gasUserNumber, province, city, district, detailedAddress });

            if (!name) {
                console.log('Name validation failed');
                showToast('请填写投保人姓名', 'error');
                return;
            }
            if (!idType) {
                console.log('ID type validation failed');
                showToast('请选择证件类型', 'error');
                return;
            }
            if (!idNumber) {
                console.log('ID number validation failed');
                showToast('请填写投保人证件号码', 'error');
                return;
            }
            // 身份证格式验证
            if (idType === 'idcard' && !/^\d{17}[\dXx]$/.test(idNumber)) {
                console.log('ID card format validation failed');
                showToast('请填写正确的身份证号码格式', 'error');
                return;
            }
            if (!gender) {
                console.log('Gender validation failed');
                showToast('请选择投保人性别', 'error');
                return;
            }
            if (!birthDate) {
                console.log('Birth date validation failed');
                showToast('请填写投保人出生日期', 'error');
                return;
            }
            if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
                console.log('Phone validation failed');
                showToast('请填写正确的手机号码', 'error');
                return;
            }
            if (!code) {
                console.log('Code validation failed');
                showToast('请填写验证码', 'error');
                return;
            }
            if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                console.log('Email validation failed');
                showToast('请填写正确的电子邮箱', 'error');
                return;
            }
            if (!gasUserNumber) {
                console.log('Gas user number validation failed');
                showToast('请填写液化气用户（卡）号', 'error');
                return;
            }
            if (!province || !city || !district) {
                console.log('Address validation failed');
                showToast('请完整选择被保险家庭地址的省市区', 'error');
                return;
            }
            if (!detailedAddress) {
                console.log('Detailed address validation failed');
                showToast('请填写详细地址', 'error');
                return;
            }

            // 验证必须阅读文件
            const readAllElement = document.getElementById('readAllDocuments');
            if (!readAllElement) {
                console.log('Read all documents element not found');
                showToast('页面元素错误，请刷新页面重试', 'error');
                return;
            }
            if (!readAllElement.checked) {
                console.log('Documents not read validation failed');
                showToast('请先阅读完所有必须阅读的文件', 'error');
                return;
            }

            console.log('All validations passed, saving data...');

            // 保存保障方案相关数据
            localStorage.setItem('selectedPlan', currentPlan);
            localStorage.setItem('planName', plans[currentPlan].name);
            localStorage.setItem('insuranceQuantity', currentQuantity);
            localStorage.setItem('totalPremium', plans[currentPlan].premium * currentQuantity);
            
            // 保存保险期间数据
            localStorage.setItem('startDate', startDate);
            localStorage.setItem('endDate', endDate);
            localStorage.setItem('insurancePeriodLabel', '1年');
            
            // 保存投保人信息（燃气险版本）
            const personalInfo = {
                personName: name,
                idTypeText: idTypeSelect.options[idTypeSelect.selectedIndex].text,
                idNumber: idNumber,
                genderText: gender === 'male' ? '男' : '女',
                birthDate: birthDate,
                phone: phone,
                email: email,
                gasUserNumber: gasUserNumber,
                address: {
                    province: province,
                    city: city,
                    district: district,
                    detailedAddress: detailedAddress,
                    fullAddress: `${provinceElement.options[provinceElement.selectedIndex].text} ${cityElement.options[cityElement.selectedIndex].text} ${districtElement.options[districtElement.selectedIndex].text} ${detailedAddress}`
                }
            };
            localStorage.setItem('personalInfo', JSON.stringify(personalInfo));
            localStorage.setItem('userType', 'personal');
            
            // 保存产品信息
            localStorage.setItem('productName', '液化气用户家财险');
            localStorage.setItem('insurer', '人保财险');
            localStorage.setItem('insuranceObject', '家庭液化气安全');

            console.log('Data saved successfully, showing success message...');
            showToast('验证通过，进入支付页面', 'success');
            setTimeout(() => {
                console.log('Redirecting to payment.html...');
                window.location.href = 'payment.html';
            }, 1500);
        }

        // 显示提示信息
        function showToast(message, type = 'info') {
            // 移除已存在的toast
            const existingToasts = document.querySelectorAll('.custom-toast');
            existingToasts.forEach(toast => toast.remove());
            
            // 创建toast元素
            const toast = document.createElement('div');
            toast.className = 'custom-toast';
            
            // 设置样式
            toast.style.cssText = `
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                z-index: 10000;
                padding: 12px 20px;
                border-radius: 8px;
                color: white;
                font-size: 14px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                max-width: 90%;
                text-align: center;
                opacity: 0;
                transition: opacity 0.3s ease;
            `;
            
            // 根据类型设置背景色
            if (type === 'error') {
                toast.style.backgroundColor = '#ef4444';
                toast.innerHTML = message;
            } else if (type === 'success') {
                toast.style.backgroundColor = '#22c55e';
                toast.innerHTML = message;
            } else {
                toast.style.backgroundColor = '#3b82f6';
                toast.innerHTML = message;
            }
            
            // 添加到页面
            document.body.appendChild(toast);
            
            // 显示动画
            setTimeout(() => {
                toast.style.opacity = '1';
            }, 10);
            
            // 2秒后自动隐藏
            setTimeout(() => {
                toast.style.opacity = '0';
                setTimeout(() => {
                    if (toast && toast.parentNode) {
                        toast.parentNode.removeChild(toast);
                    }
                }, 300);
            }, 2000);
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 显示进入投保流程提示弹窗
            setTimeout(showEntranceModal, 500);

            // 初始化性别按钮
            initPersonalGenderButtons();

            // 初始化保险起期为明天零时
            const tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
            tomorrow.setHours(0, 0, 0, 0);
            document.getElementById('startDate').value = tomorrow.toISOString().slice(0, 16);
            updateEndDate();

            // 初始化保障方案
            updatePlanDetails();
            updatePremium();
            

        });
    </script>
</body>
</html>